<template>
  <div class="app-container">
    <div class="main-layout">
      <!-- 左侧用能单元树 -->
      <div class="left-panel">
        <EnergyUnitTree
          ref="energyUnitTreeRef"
          title="用能单元结构"
          :show-node-actions="false"
          :show-expand-toggle="false"
          :auto-select-first="true"
          @node-click="handleNodeClick"
        />
      </div>

      <!-- 右侧分析内容 -->
      <div class="right-panel">
        <!-- 标题 -->
        <div class="analysis-header">
      <h2>负荷分析</h2>
        </div>

        <!-- 筛选区域 -->
        <div class="filter-section">
          <div class="filter-row">
            <!-- 日期筛选 -->
            <div class="date-filter">
              <el-date-picker
                v-model="selectedDate"
                type="date"
                placeholder="选择日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                style="width: 200px"
              />
            </div>

            <!-- 设备选择 -->
            <div class="device-select">
              <el-select
                v-model="selectedDeviceId"
                placeholder="选择电表"
                clearable
                style="width: 200px"
                @change="handleDeviceChange"
              >
                <el-option
                  v-for="device in deviceList"
                  :key="device.deviceId"
                  :label="device.groupDeviceName || device.deviceName"
                  :value="device.deviceId"
                />
              </el-select>
            </div>

            <!-- 搜索按钮 -->
            <el-button type="primary" icon="Search" @click="handleSearch">
              搜索
            </el-button>
          </div>
        </div>
    
        <!-- 内容区域 -->
        <div class="content-area">
          <!-- 图表区域 -->
          <div class="chart-container">
            <div ref="chartRef" class="chart" style="height: 400px" v-if="chartData.length > 0"></div>
            <div class="chart-empty" v-else>
              <el-empty description="暂无数据" />
            </div>
          </div>

          <!-- 统计数据区域 -->
          <div class="statistics-container">
            <el-card class="stats-card">
              <div class="stats-grid">
                <div class="stat-item">
                  <div class="stat-label">最大负荷</div>
                  <div class="stat-value">{{ statistics.maxLoad }} kW</div>
                  <div class="stat-time">
                    发生时间: {{ statistics.maxLoadTime }}
                  </div>
                </div>
                <div class="stat-item">
                  <div class="stat-label">最小负荷</div>
                  <div class="stat-value">{{ statistics.minLoad }} kW</div>
                  <div class="stat-time">
                    发生时间: {{ statistics.minLoadTime }}
                  </div>
                </div>
                <div class="stat-item">
                  <div class="stat-label">平均负荷</div>
                  <div class="stat-value">{{ statistics.avgLoad }} kW</div>
                </div>
                <div class="stat-item">
                  <div class="stat-label">负荷率</div>
                  <div class="stat-value">{{ statistics.loadFactor }}%</div>
                </div>
              </div>
            </el-card>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, nextTick } from "vue";
import { ElMessage } from "element-plus";
import * as echarts from "echarts";
import { getDeviceGroupList } from "@/api/deviceManage/energyUnit";
import { getDeviceRealtimeData, getDeviceHistoryData } from "@/api/stat/realtime";
import EnergyUnitTree from "@/components/EnergyUnitTree/index.vue";

// 响应式数据
const selectedDate = ref("");
const selectedDeviceId = ref("");
const chartRef = ref(null);
const energyUnitTreeRef = ref(null);

// 用能单元和设备相关数据
const selectedNode = ref(null);
const deviceList = ref([]);
const deviceLoading = ref(false);

// 防重复调用标志
const isLoadingDevices = ref(false);

// 图表数据
const chartData = ref([]);

// 统计数据（卡片展示）
const statistics = reactive({
  maxLoad: "-",
  maxLoadTime: "-",
  minLoad: "-",
  minLoadTime: "-",
  avgLoad: "-",
  loadFactor: "-",
});

// 图表实例
let chartInstance = null;

// 方法
// 树相关函数
const handleNodeClick = (data) => {
  if (!data || !data.groupName) return;
  selectedNode.value = data;
  loadUnitDevices(data.groupId);
};

const loadUnitDevices = (groupId) => {
  if (!groupId) {
    deviceList.value = [];
    selectedDeviceId.value = "";
    chartData.value = [];
    statistics.maxLoad = "-";
    statistics.maxLoadTime = "-";
    statistics.minLoad = "-";
    statistics.minLoadTime = "-";
    statistics.avgLoad = "-";
    statistics.loadFactor = "-";
    
    // 清空图表
    if (chartInstance) {
      chartInstance.dispose();
      chartInstance = null;
    }
    return;
  }

  // 防重复调用 - 只有在相同groupId时才跳过
  if (isLoadingDevices.value && selectedNode.value?.groupId === groupId) {
    console.log("相同节点设备列表正在加载中，跳过重复调用");
    return;
  }

  // 切换用能单元时，先清空当前选中的设备和数据
  selectedDeviceId.value = "";
  chartData.value = [];
  statistics.maxLoad = "-";
  statistics.maxLoadTime = "-";
  statistics.minLoad = "-";
  statistics.minLoadTime = "-";
  statistics.avgLoad = "-";
  statistics.loadFactor = "-";
  
  // 清空图表
  if (chartInstance) {
    chartInstance.dispose();
    chartInstance = null;
  }

  isLoadingDevices.value = true;
  deviceLoading.value = true;

  // 调用真实的设备接口
  getDeviceGroupList(groupId)
    .then((response) => {
      deviceList.value = response.data || [];
      // 默认选中第一个设备
      if (deviceList.value.length > 0) {
        selectedDeviceId.value = deviceList.value[0].deviceId;
        // 如果有选中的日期，自动加载新设备的数据
        if (selectedDate.value) {
          handleDeviceChange(deviceList.value[0].deviceId);
        }
      }
      deviceLoading.value = false;
      isLoadingDevices.value = false;
    })
    .catch((error) => {
      console.error("获取分组设备失败:", error);
      deviceList.value = [];
      selectedDeviceId.value = "";
      chartData.value = [];
      statistics.maxLoad = "-";
      statistics.maxLoadTime = "-";
      statistics.minLoad = "-";
      statistics.minLoadTime = "-";
      statistics.avgLoad = "-";
      statistics.loadFactor = "-";
      
      // 清空图表
      if (chartInstance) {
        chartInstance.dispose();
        chartInstance = null;
      }
      
      deviceLoading.value = false;
      isLoadingDevices.value = false;
    });
};

const handleDeviceChange = (deviceId) => {
  if (!deviceId) {
    selectedDeviceId.value = "";
    chartData.value = [];
    statistics.maxLoad = "-";
    statistics.maxLoadTime = "-";
    statistics.minLoad = "-";
    statistics.minLoadTime = "-";
    statistics.avgLoad = "-";
    statistics.loadFactor = "-";
    
    // 清空图表
    if (chartInstance) {
      chartInstance.dispose();
      chartInstance = null;
    }
    return;
  }
  // 设备切换时重新加载数据
  if (selectedDate.value) {
    loadData();
  }
};

const handleSearch = () => {
  if (!selectedDate.value) {
    ElMessage.warning("请选择日期");
    return;
  }
  if (!selectedDeviceId.value) {
    ElMessage.warning("请选择设备");
    return;
  }

  loadData();
};

// 加载数据
const loadData = async () => {
  if (!selectedDeviceId.value) {
    return;
  }
  
  try {
    // 计算时间范围：当天00:00:00到当天23:59:59
    const startOfDay = Math.floor(new Date(selectedDate.value + ' 00:00:00').getTime() / 1000); // 当天0点，转换为秒
    const endOfDay = Math.floor(new Date(selectedDate.value + ' 23:59:59').getTime() / 1000); // 当天23:59:59，转换为秒
    
    console.log("时间范围计算:", {
      selectedDate: selectedDate.value,
      startOfDay: startOfDay,
      endOfDay: endOfDay,
      startTime: new Date(startOfDay * 1000).toLocaleString(),
      endTime: new Date(endOfDay * 1000).toLocaleString()
    });
    
    // 固定调用 ActivePower_Total
    const tags = "ActivePower_Total";
    
    const params = {
      deviceId: selectedDeviceId.value,
      tags: tags,
      start: startOfDay,
      end: endOfDay,
      curPage: 1,
      pagesize: 1000 // 获取足够多的数据
    };
    
    const response = await getDeviceHistoryData(params);
    
    if (response.data && response.data.dataList && response.data.dataList.list) {
      // 处理API返回的数据，先倒序排列（因为第一条是最新时间）
      const processedData = response.data.dataList.list.reverse().map(item => {
        return {
          time: formatTimeForChart(item.date, item.dateStr),
          timestamp: item.date,
          powerFactor: parseFloat(item.data?.PowerFactor_Total || 0)
        };
      });
      
      chartData.value = processedData;
      
      // 更新统计数据
      updateStatistics();
      
      // 重新渲染图表
      nextTick(() => {
        initChart();
      });
    } else {
      chartData.value = [];
      ElMessage.info("暂无历史数据");
    }
  } catch (error) {
    console.error("加载数据失败:", error);
    ElMessage.error("加载数据失败");
  }
};

// 格式化时间用于图表显示（只显示小时和分钟）
const formatTimeForChart = (timestamp, dateStr = null) => {
  // 优先使用 dateStr 字段
  if (dateStr) {
    // 解析 dateStr 格式，如 "2025-10-10 10" 或 "2025-10-10 10:30"
    const parts = dateStr.split(' ');
    if (parts.length >= 2) {
      const timePart = parts[1];
      if (timePart.includes(':')) {
        // 如果包含分钟，直接返回
        return timePart;
      } else {
        // 如果只有小时，补全分钟为00
        return `${timePart.padStart(2, '0')}:00`;
      }
    }
  }

  // 如果没有 dateStr 或解析失败，使用时间戳
  if (!timestamp) return "--";

  let date;

  // 如果是字符串格式的日期（如 "2025-10-01"）
  if (typeof timestamp === "string") {
    // 如果只有日期没有时间，添加默认时间
    if (timestamp.length === 10) {
      timestamp += " 00:00:00";
    }
    date = new Date(timestamp);
  } else {
    // 如果是数字时间戳
    const ms = timestamp > 1e12 ? timestamp / 1e6 : timestamp;
    date = new Date(ms);
  }

  // 检查日期是否有效
  if (isNaN(date.getTime())) {
    return "--";
  }

  return date.toLocaleString("zh-CN", {
    hour: "2-digit",
    minute: "2-digit",
  });
};

// 更新统计数据
const updateStatistics = () => {
  if (chartData.value.length === 0) return;

  // 计算负荷的统计数据
  const powerFactorData = chartData.value.map((item) => item.powerFactor);

  // 计算最大值、最小值、平均值
  const maxLoad = Math.max(...powerFactorData);
  const minLoad = Math.min(...powerFactorData);
  const avgLoad = powerFactorData.reduce((sum, val) => sum + val, 0) / powerFactorData.length;
  const loadFactor = ((avgLoad / maxLoad) * 100).toFixed(2);

  statistics.maxLoad = maxLoad.toFixed(2);
  statistics.minLoad = minLoad.toFixed(2);
  statistics.avgLoad = avgLoad.toFixed(2);
  statistics.loadFactor = loadFactor;

  // 找到最大最小负荷的时间
  const maxLoadItem = chartData.value.find((item) => item.powerFactor === maxLoad);
  const minLoadItem = chartData.value.find((item) => item.powerFactor === minLoad);

  if (maxLoadItem) {
    statistics.maxLoadTime = maxLoadItem.time;
  }
  if (minLoadItem) {
    statistics.minLoadTime = minLoadItem.time;
  }
};

// 初始化图表
const initChart = () => {
  if (!chartRef.value) return;

  if (chartInstance) {
    chartInstance.dispose();
  }

  chartInstance = echarts.init(chartRef.value);

  const option = {
    title: {
      text: "负荷分析",
      left: "center",
    },
    tooltip: {
      trigger: "axis",
      formatter: function (params) {
        const data = params[0];
        return `${data.axisValue}<br/>负荷: ${data.value}`;
      },
    },
    xAxis: {
      type: "category",
      data: chartData.value.map((item) => item.time), // 直接使用格式化后的时间
    },
    yAxis: {
      type: "value",
      name: "负荷",
      axisLabel: {
        formatter: "{value}",
      },
    },
    series: [
      {
        name: "负荷",
        type: "line",
        data: chartData.value.map((item) => item.powerFactor),
        smooth: true,
        lineStyle: {
          color: "#4fdaca",
        },
        itemStyle: {
          color: "#4fdaca",
        },
      },
    ],
  };

  chartInstance.setOption(option);

  // 响应式调整
  window.addEventListener("resize", () => {
    chartInstance?.resize();
  });
};

// 页面初始化
onMounted(() => {
  // 设置默认日期为今天
  const today = new Date();
  selectedDate.value = today.toISOString().split("T")[0];
  // 树组件会自动加载数据
});
</script>

<style lang="scss" scoped>
@import "@/assets/styles/variables.module.scss";

.app-container {
  padding: 0;
  background: $base-menu-background;
  height: 100%;
}

.main-layout {
  display: flex;
  gap: 15px;
  padding: 10px;
  height: 100%;
  box-sizing: border-box;
}

// 左侧面板
.left-panel {
  flex: 0 0 20%;
  background: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  height: 100%;
}

// 右侧面板
.right-panel {
  flex: 1;
  background: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  height: 100%;

  .analysis-header {
    padding: 20px 30px;
    border-bottom: 1px solid #e4e7ed;
    background: #f8f9fa;

    h2 {
      font-size: 20px;
    font-weight: 600;
      color: #2c3e50;
    margin: 0;
  }
}

  .filter-section {
    padding: 20px 30px;
    border-bottom: 1px solid #e4e7ed;

    .filter-row {
      display: flex;
      align-items: center;
      gap: 20px;
      margin-bottom: 15px;

      .date-filter,
      .device-select {
        :deep(.el-input__wrapper) {
          border-radius: 6px;
          transition: all 0.3s ease;

          &:focus-within {
            box-shadow: 0 0 0 2px rgba(79, 218, 202, 0.2);
          }
        }
      }

      .el-button {
        border-radius: 6px;
        font-weight: 500;
        padding: 8px 20px;

        &.el-button--primary {
          background: linear-gradient(135deg, #4fdaca 0%, #32b7cb 100%);
          border: none;
          color: #ffffff;

          &:hover {
            background: linear-gradient(135deg, #3bc4b3 0%, #2aa3b8 100%);
            color: #ffffff;
          }
        }
      }
    }
  }

.content-area {
    flex: 1;
    padding: 20px 30px;
    display: flex;
    flex-direction: column;

    .chart-container {
      flex: 1;
      margin-bottom: 20px;

      .chart {
        width: 100%;
        border-radius: 8px;
        background: #ffffff;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
      }
      
      .chart-empty {
        display: flex;
        align-items: center;
        justify-content: center;
        height: 400px;
        background: #f8f9fa;
        border-radius: 8px;
        border: 1px dashed #d9d9d9;
      }
    }

    .statistics-container {
      margin-bottom: 20px;
      
      .stats-card {
        border-radius: 8px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

        :deep(.el-card__body) {
          padding: 20px;
        }

        .stats-grid {
          display: grid;
          grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
          gap: 20px;

          .stat-item {
            padding: 20px;
            background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
            border-radius: 8px;
            text-align: center;
            border: 1px solid #e4e7ed;

            .stat-label {
              font-size: 14px;
              color: #6c757d;
              margin-bottom: 8px;
              font-weight: 500;
            }

            .stat-value {
              font-size: 24px;
              font-weight: 700;
              color: #2c3e50;
              margin-bottom: 4px;
            }

            .stat-time {
              font-size: 12px;
              color: #6c757d;
              font-style: italic;
            }
          }
        }
      }
    }

    .table-container {
      margin-bottom: 20px;
      
      .table-card {
        border-radius: 8px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

        :deep(.el-card__header) {
          padding: 16px 20px;
          border-bottom: 1px solid #e4e7ed;
          background: #f8f9fa;

          .table-header {
            font-size: 16px;
            font-weight: 600;
            color: #2c3e50;
          }
        }

        :deep(.el-card__body) {
          padding: 0;
        }

        :deep(.el-table) {
          border-radius: 0 0 8px 8px;
          overflow: hidden;

          .el-table__header {
            th {
              background: #f8f9fa;
              color: #2c3e50;
              font-weight: 600;
              border-bottom: 2px solid #e4e7ed;
            }
          }

          .el-table__body {
            tr {
              transition: all 0.3s ease;

              &:hover {
                background: #f5f7fa;
              }
            }
          }
        }
      }
    }
  }
}

// 响应式设计
@media (max-width: 1200px) {
  .main-layout {
    flex-direction: column;
  }

  .left-panel {
    width: 100%;
    height: 200px;
    border-right: none;
    border-bottom: 1px solid #e4e7ed;
  }

  .right-panel {
    height: calc(100vh - 200px);
  }
}

@media (max-width: 768px) {
  .right-panel {
    .filter-section {
      padding: 15px;

      .filter-row {
        flex-direction: column;
        align-items: stretch;
        gap: 15px;

        .time-granularity,
        .date-filter,
        .device-select {
          width: 100%;
        }
      }
    }

    .content-area {
      padding: 15px;

      .statistics-container {
        .stats-grid {
          grid-template-columns: 1fr;
        }
      }
    }
  }
}
</style>
